package socket;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Server{
    private ServerSocket serverSocket;
//    ArrayList<Socket> sockets=new ArrayList<Socket>();
    public Server() {
        try {
            serverSocket = new ServerSocket(8888);
            System.out.println("服务器端已开启！");
            System.out.println("等待客户端连接！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        Socket socket=null;
        while (true){
            try {
                socket=serverSocket.accept();
                Add add=new Add(socket);
                add.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Server server=new Server();
        server.start();
    }

    class Add extends Thread{
        Socket socket;
        InputStream input;

        Add(Socket socket){
            this.socket=socket;
        }

        @Override
        public void run() {
            String s2=socket.getLocalAddress().getHostName();
            try {
                while (true){
                    System.out.println(s2+"已连接");
                    input = socket.getInputStream();
                    int len=-1;
                    byte[] bytes=new byte[1024];
                    while ((len=input.read(bytes))!=-1){
                        if (new String(bytes,0,len).equals("BBL")){
                            break;
                        }
                        System.out.println(s2+"说："+new String(bytes,0,len));
                    }
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                System.out.println(s2+"断开连接");
                if (socket!=null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

